package mqtt

import (
	mqtt "github.com/eclipse/paho.mqtt.golang"
)

type Client struct {
	client mqtt.Client
}

func (m *Client) Connect(url string) error {
	mqttClient := mqtt.NewClient(mqtt.NewClientOptions().AddBroker(url))
	if token := mqttClient.Connect(); token.Wait() && token.Error() != nil {
		return token.Error()
	}
	m.client = mqttClient
	return nil
}

func (m *Client) Close() {
	if m.client != nil {
		m.client.Disconnect(250)
	}
}

func (m *Client) Publish(topic string, qos byte, retained bool, payload interface{}) error {
	if token := m.client.Publish(topic, qos, retained, payload); token.Wait() && token.Error() != nil {
		return token.Error()
	}
	return nil
}
func (m *Client) Subscribe(topic string, qos byte, callback mqtt.MessageHandler) error {
	if token := m.client.Subscribe(topic, qos, callback); token.Wait() && token.Error() != nil {
		return token.Error()
	}
	return nil
}
